<?php
/**************************************************************************
 *
 *   Copyright 2010 American Public Media Group
 *
 *   This file is part of AIR2.
 *
 *   AIR2 is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   AIR2 is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with AIR2.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************/


/**
 * BatchRelated
 *
 * An item related to BatchItem.  For example, if the BatchItem is a
 * "BatchSource", one of it's related items might be a "SourceAnnotation".
 *
 * @property integer $brel_bitem_id
 * @property string $brel_type
 * @property integer $brel_xid
 * @property string $brel_status
 * @property integer $brel_cre_user
 * @property integer $brel_upd_user
 * @property timestamp $brel_cre_dtim
 * @property timestamp $brel_upd_dtim
 * @property BatchItem $BatchItem
 * @author rcavis
 * @package default
 */
class BatchRelated extends AIR2_Record {
    /* code_master values */
    public static $STATUS_ACTIVE = 'A';
    public static $STATUS_INACTIVE = 'F';

    public static $TYPES = array(
        'S' => array(
            'A' => 'SrcAnnotation',
            'M' => 'SrcMailAddress',
            'R' => 'SrcResponse',
            'S' => 'SrcResponseSet',
        ),
        'U' => array(
            'E' => 'UserEmailAddress',
            'P' => 'UserPhoneNumber',
        ),
    );


    /**
     * Set the table columns
     */
    public function setTableDefinition() {
        $this->setTableName('batch_related');
        $this->hasColumn('brel_bitem_id', 'integer', 4, array(
                'primary' => true,
            ));
        $this->hasColumn('brel_type', 'string', 1, array(
                'fixed' => true,
                'primary' => true,
            ));
        $this->hasColumn('brel_xid', 'integer', 4, array(
                'primary' => true,
            ));
        $this->hasColumn('brel_status', 'string', 1, array(
                'fixed' => true,
                'notnull' => true,
                'default' => self::$STATUS_ACTIVE,
            ));
        $this->hasColumn('brel_cre_user', 'integer', 4, array(
                'notnull' => true,
            ));
        $this->hasColumn('brel_upd_user', 'integer', 4, array(

            ));
        $this->hasColumn('brel_cre_dtim', 'timestamp', null, array(
                'notnull' => true,
            ));
        $this->hasColumn('brel_upd_dtim', 'timestamp', null, array(

            ));

        parent::setTableDefinition();
    }


    /**
     * Set table relations
     */
    public function setUp() {
        parent::setUp();
        $this->hasOne('BatchItem', array(
                'local' => 'brel_bitem_id',
                'foreign' => 'bitem_id',
                'onDelete' => 'CASCADE'
            ));

        //DON'T call during setup ... will create constraints!!
        //$this->setupRelated(BatchRelated::$BATCH_TYPE);
        //BatchRelated::$BATCH_TYPE = null;
    }


    /**
     * Sets the generic "brel_xid" on this table to a specific relation based
     * on batch type.
     *
     * @param string  $batch_type
     * @param Doctrine_Table $tbl        (optional)
     */
    public static function setupRelated($batch_type, $tbl=null) {
        if (!$tbl) $tbl = Doctrine::getTable('BatchRelated');

        // get each foreign column --- model must have a primary key!
        if (isset(BatchRelated::$TYPES[$batch_type])) {
            foreach (BatchRelated::$TYPES[$batch_type] as $code => $model) {
                $def = Doctrine::getTable($model)->getIdentifierColumnNames();
                if (count($def) == 1) {
                    $tbl->hasOne($model, array('local' => 'brel_xid', 'foreign' => $def[0]));
                }
            }
        }
    }


    /**
     * Joins a BatchRelated to it's external reference in a Doctrine Query.
     *
     * @param AIR2_Query $q          (reference) query to add the join to
     * @param string  $bitem_type the type of bitem (NOT the batch type)
     * @param string  $alias      (optional) alias of BatchItem in the query
     */
    public static function joinRelated(&$q, $bitem_type, $alias=null) {
        $q->getSqlQuery(); // trigger parser
        $c = $q->getQueryComponent($alias);
        $t = isset($c['table']) ? $c['table'] : null;
        BatchRelated::setupRelated($bitem_type, $t);

        // join ALL the possible relations for this bitem_type, using 'WITH'
        // to make sure the ones that aren't legitimate are NULL
        if (isset(BatchRelated::$TYPES[$bitem_type])) {
            foreach (BatchRelated::$TYPES[$bitem_type] as $code => $model) {
                if ($alias)
                    $q->leftJoin("$alias.$model rel$code WITH $alias.brel_type = '$code'");
                else
                    $q->leftJoin("$model rel$code WITH brel_type = '$code'");

                // TODO: Generalize these joins
                switch ($model) {
                case 'SrcResponseSet':
                    $q->leftJoin("rel$code.Inquiry");
                    break;
                case 'SrcResponse':
                    $q->leftJoin("rel$code.Question");
                    break;
                default:
                    break;
                }
            }
        }
    }


}
